﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Core.FrameWork.Commons.Hepler.Validate
{
    public class ValidateHelper
    {
        /// <summary>
        /// 判断是否为有效的邮件地址
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsValidEmail(string email)
        {
            return Regex.IsMatch(email, @"^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 判断是否为有效的身份证号
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsIDNumber(string IDNumber)
        {
            return Regex.IsMatch(IDNumber, @"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$");
        }

        /// <summary>
        /// 验证是否包含数字、网址、邮箱 
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public static bool SimpleFilter(string word)
        {
            if (string.IsNullOrEmpty(word))
            {
                return true;
            }
            string str = ToDBC(word);

            return !(IsContainUrl(str) || IsContainNum(str));
        }

        /// <summary>
        /// 是否包含网址
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsContainUrl(string str)
        {
            var reg = Regex.Match(str, @"([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
            return reg.Success;
        }

        /// <summary>
        /// 是否包含数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsContainNum(string str)
        {
            Regex reg = new Regex(@"[\d一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾①②③④⑤⑥⑦⑧⑨⑩⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛❶❷❸❹❺❻❼❽❾❿㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ]+");
            return reg.IsMatch(str);
        }

        /// <summary>
        /// 是否包含数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsContainNumber(string str)
        {
            return Regex.IsMatch(str, @".*[0-9]+.*");
        }

        /// <summary>
        /// 是否有电话号码嫌疑
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsContainPhone(string str)
        {
            Regex reg = new Regex(@"[\d①②③④⑤⑥⑦⑧⑨⑩⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛❶❷❸❹❺❻❼❽❾❿㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ]+");
            return reg.IsMatch(str);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 验证是否为手机号
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool IsMobile(String mobile)
        {
            return Regex.IsMatch(mobile, "^1([3456789][0-9])[0-9]{8}$");
        }
        /// <summary>
        /// 验证固话的数据格式
        /// </summary>
        /// <param name="str_telephone"></param>
        /// <returns></returns>
        public static bool IsTelephone(string str_telephone)
        {
            return Regex.IsMatch(str_telephone, @"^(0[0-9]{2,3}|\(0[0-9]{2,3}\))(\-)?([2-9][0-9]{6,7})$");
        }
        /// <summary>
        /// 验证是否为不包含-的座机
        /// </summary>
        /// <param name="telephone"></param>
        /// <returns></returns>
        public static bool IsTEL(string telephone)
        {
            return Regex.IsMatch(telephone, "\\d{3}\\d{8}|\\d{4}-\\d{7}");
        }

        /// <summary>
        /// 验证是否为图片格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsImg(string str)
        {
            string[] imgext = new string[] { "jpg", "jpeg", "gif", "png", "bmp" };
            if (imgext.Contains(str.ToLower()))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 只含有汉字、数字、字母、下划线，下划线位置不限
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsChNumEn(string str)
        {
            return Regex.IsMatch(str, "^[a-zA-Z0-9_\u4e00-\u9fa5]+$");
        }

        /// <summary>
        /// 验证是否为网址
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsUrl(string url)
        {
            return Regex.IsMatch(url, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?");
        }

        /// <summary>
        /// Base64 解码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Base64StringDecode(string input)
        {
            byte[] bytes = Convert.FromBase64String(input);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// Base64 编码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Base64StringEncode(string input)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
        }

        private static readonly char[] base64CodeArray = new char[]
          {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4',  '5', '6', '7', '8', '9', '+', '/', '='
          };

        /// <summary>  
        /// 是否base64字符串  
        /// </summary>  
        /// <param name="base64Str">要判断的字符串</param>  
        /// <param name="bytes">字符串转换成的字节数组</param>  
        /// <returns></returns>  
        public static bool IsBase64(string base64Str)
        {
            byte[] bytes = null;
            if (string.IsNullOrEmpty(base64Str))
            {
                return false;
            }
            else
            {
                if (base64Str.Contains(","))
                    base64Str = base64Str.Split(',')[1];
                if (base64Str.Length % 4 != 0)
                    return false;
                if (base64Str.Any(c => !base64CodeArray.Contains(c)))
                    return false;
            }
            try
            {
                bytes = Convert.FromBase64String(base64Str);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        /// <summary>
        /// 将Base64字符串转换为二进制流
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static MemoryStream Base64ToStream(string strBase64, out bool flag, out string ImgExtend)
        {
            MemoryStream stream = null;
            flag = false;
            ImgExtend = string.Empty;
            string str = strBase64;
            //标准的Base64图片字符串，包含头信息：data:image/jpg;base64,
            if (str.Contains(","))
            {
                string[] tempImgStr = str.Split(',');
                str = tempImgStr[1];
                //实际的图片扩展名
                ImgExtend = tempImgStr[0].Split('/')[1].Split(';')[0];
                //验证是否为图片格式
                flag = IsImg(ImgExtend);
            }
            if (flag)
            {
                //Base64解密为二进制并放入流中
                stream = new MemoryStream(Convert.FromBase64String(str));
            }
            return stream;
        }

        /// <summary>
        /// Base64文件KB大小
        /// </summary>
        /// <param name="strBase64"></param>
        /// <returns></returns>
        public static int Base64Length(string strBase64)
        {
            var baseStr = strBase64.Split(',')[1];
            var eqTagIndex = baseStr.IndexOf("=");
            baseStr = eqTagIndex != -1 ? baseStr.Substring(0, eqTagIndex) : baseStr;
            return (baseStr.Length - (baseStr.Length / 8) * 2) / 1024;
        }

        /// <summary>
        /// Base64文件扩展名
        /// </summary>
        /// <param name="strBase64"></param>
        /// <returns></returns>
        public static string Base64Extend(string strBase64)
        {
            return strBase64.Split(';')[0].Split('/')[1].ToLower();
        }

        /// <summary>
        /// 随机生成文件名 
        /// </summary>
        /// <returns></returns>
        public static string RandomFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            serial.Append("_" + rd.Next(0, 999999).ToString());
            return serial.ToString();
        }

        /// <summary>
        /// 移除字符串的HTML代码
        /// </summary>
        /// <param name="Htmlstr"></param>
        /// <returns></returns>
        public static string Nohtml(string Htmlstr)
        {
            if (Htmlstr == null)
            {
                return "";
            }

            Htmlstr = Regex.Replace(Htmlstr, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstr = Regex.Replace(Htmlstr, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstr = Htmlstr.Replace("<", "");
            Htmlstr = Htmlstr.Replace(">", "");
            Htmlstr = Htmlstr.Replace("\r\n", "");
            Htmlstr = Htmlstr.Replace("\n", "");
            Htmlstr = Htmlstr.Replace("\n3", "");
            Htmlstr = Htmlstr.Replace("\r", "");
            Htmlstr = Htmlstr.Replace("   ", "");
            return Htmlstr;
        }

        /// <summary>
        /// 重写输出数据字体颜色
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="forecolor"></param>
        /// <param name="backcolor"></param>
        public static void WriteLine(string msg, ConsoleColor forecolor = ConsoleColor.Green, ConsoleColor backcolor = ConsoleColor.Black)
        {
            Console.ForegroundColor = forecolor;
            Console.BackgroundColor = backcolor;
            Console.WriteLine(msg);
            Console.ForegroundColor = ConsoleColor.Gray;
        }

    }
}
